package cn.school.web;

import cn.school.entity.Admin;
import cn.school.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int num=this.getLoginNums(req, resp);
        if(num>3){
            resp.sendRedirect("login.jsp?msg="+ URLEncoder.encode("登录太频繁，请明天再试！","utf-8"));
            return;
        }
         String u=req.getParameter("username");
         String p=req.getParameter("password");
        Admin admin = AdminService.INST.login(u, p);
        if(admin==null){
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
            return;
        }
        Cookie c=new Cookie("loginNums","0");
        //c.setMaxAge(0);
        resp.addCookie(c);
        req.getSession().setAttribute("USER",admin);
        resp.sendRedirect("main.jsp");
    }

    public int getLoginNums(HttpServletRequest request,HttpServletResponse
                             resp){
        Cookie cr[]=request.getCookies();
        //假定，那个cookie的名字叫 visitNums
        Cookie c=null;
        for(int i=0;cr!=null&&i<cr.length;i++){
            if(cr[i].getName().equals("loginNums")){
                c=cr[i];
                break;
            }
        }
        if(c==null){
            c=new Cookie("loginNums","1");
        }else{
            c.setValue(String.valueOf(Integer.parseInt(c.getValue())+1));
        }
        //再发给浏览器
        c.setMaxAge(3600*24);
        resp.addCookie(c);
        return Integer.valueOf(c.getValue());
    }
}
